#!/bin/bash
if [ $# -eq 0 ]; then
    echo "Usage: mkpkg directory_name"
else
    DIR="$(dirname "$(readlink -f ${BASH_SOURCE[0]})")/${@}"
    TMPDIR=/tmp/tmp.$(( $RANDOM * 19318203981230 + 40 ))
    PLUGIN=$(basename ${DIR})
    ARCHIVE="$(dirname $(dirname ${DIR}))/pkg"
    DESTDIR="$TMPDIR/usr/local/emhttp/plugins/${PLUGIN}"
    PLG_FILE="$(dirname $(dirname ${DIR}))/${PLUGIN}.plg"
    VERSION=$(date +"%Y.%m.%d")
    ARCH="-x86_64"
    PACKAGE="${ARCHIVE}/${PLUGIN}-${VERSION}${ARCH}.txz"
    MD5="${ARCHIVE}/${PLUGIN}-${VERSION}${ARCH}.md5"

    for x in '' a b c d e d f g h ; do
        PKG="${ARCHIVE}/${PLUGIN}-${VERSION}${x}${ARCH}.txz"
        if [[ ! -f $PKG ]]; then
          PACKAGE=$PKG
          VERSION="${VERSION}${x}"
          MD5="${ARCHIVE}/${PLUGIN}-${VERSION}${ARCH}.md5"
          break
        fi
    done

    sed -i -e "s#\(ENTITY\s*version[^\"]*\).*#\1\"${VERSION}\">#" "$PLG_FILE"
    sed -i "/##&name/a\###${VERSION}" "$PLG_FILE"

    mkdir -p "${TMPDIR}/"
    cd "$DIR"
    cp --recursive --dereference . "${TMPDIR}/"
    cd "$TMPDIR/"
    makepkg -l y -c y "${PACKAGE}"
    cd "$ARCHIVE/"
    md5sum $(basename "$PACKAGE") > "$MD5"
    rm -rf "$TMPDIR"

    # Verify and install plugin package
    sum1=$(md5sum "${PACKAGE}")
    sum2=$(cat "$MD5")
    if [ "${sum1:0:32}" != "${sum2:0:32}" ]; then
      echo "Checksum mismatched.";
      rm "$MD5" "${PACKAGE}"
    else
      echo "Checksum matched."
    fi
fi